package com.sport.facilities.booking.system.core;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpHelper {
	protected final int CONN_PORT = 443;
	protected final String CONN_PROTOCOL = "HTTPS";
	protected final String URL_BASIC = "www40.polyu.edu.hk";
	protected final String USER_AGENT = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11";

	private DefaultHttpClient httpClient = null;
	private HttpHost targetHost = null;

	public HttpHelper() {
	}

	public HttpHost getTargetHost() {
		if (this.targetHost == null) {
			this.targetHost = new HttpHost(URL_BASIC, CONN_PORT, CONN_PROTOCOL);
		}
		return targetHost;
	}

	public DefaultHttpClient getClient() {
		if (this.httpClient == null) {
			this.httpClient = HttpClientFactory.getThreadSafeClient();
			// new DefaultHttpClient();
		}
		return httpClient;
	}

	public String doGet(String url) throws ParseException,
			ClientProtocolException, IOException {
		String html = "";
		// Thread.sleep(((int)(Math.random()*10))*1000);
		HttpGet httpGet = new HttpGet(url);
		html = getResponseHTML(getClient().execute(getTargetHost(), httpGet));
		return html;
	}

	public String doPost(String url, List<NameValuePair> nvps)
			throws ClientProtocolException, IOException, ParseException {
		// Thread.sleep(((int)(Math.random()*10))*1000);
		HttpPost httpPost = new HttpPost(url);
		if(nvps != null){
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));			
		}
		httpPost.setHeader("User-Agent", USER_AGENT);
		HttpResponse response = getClient().execute(getTargetHost(), httpPost);
		return getResponseHTML(response);
	}

	public String getResponseHTML(HttpResponse response) throws ParseException,
			IOException {
		HttpEntity entity = response.getEntity();
		// fnPrintHeaderForDebug(response.getAllHeaders());
		String resultHTML = EntityUtils.toString(entity);
		fnPrintHTMLForDebug(resultHTML);
		return resultHTML;
	}

	public Bitmap downloadBitmap(String url) throws IOException {
        HttpUriRequest httpGet = new HttpGet(url.toString());
        HttpResponse response = getClient().execute(getTargetHost(),httpGet);
 
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                    bytes.length);
            return bitmap;
        } else {
            throw new IOException("Download failed, HTTP response code "
                    + statusCode + " - " + statusLine.getReasonPhrase());
        }
    }
	
	/*
	 * Debug function
	 */
	private void fnPrintHeaderForDebug(Header[] headers) {
		for (Header h : headers) {
			//System.out.println(h.getName() + ": " + h.getValue());
		}
	}
	
	private void fnPrintHTMLForDebug(String resultHTML) {
		//System.out.println(resultHTML);
	}
	
	public void doLogout() {
		httpClient = null;
	}
}
